# -*- coding: UTF-8 -*-

# Copyright (C) 2009 Daniele Favara.
# Written by Daniele Favara <daniele@zeroisp.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""
TurboGears related projects and their versions
"""
import sys, os
from paste.script import command

here = os.path.abspath('.')

model_init_template = """#set the metadata of the extension to our application's metadata
import tgext.zeroisp.model as zeroisp_model
zeroisp_model.metadata = metadata
zeroisp_model.DBSession = DBSession


#get the tables and mappers
from tgext.zeroisp.model import *"""

websetup_template = """
    from tgext.zeroisp.websetup import setup_app as zeroisp_setup_app
    zeroisp_setup_app(model)
    transaction.commit()

"""


class SetupDBCommand(command.Command):


    languages = 'en,ru,fr,es'

    summary = "Add Pages Database stuff to your TG2 project"
    usage = 'paster zeroisp setup -l en,ru,fr'
    parser = command.Command.standard_parser(verbose=True)
    parser.add_option("-l", "--language",
            help="include any languages (comma separated list) [en]",
            dest="languages", default='en')
    def _get_package_name(self):
        for f in os.listdir(here):
            if f.endswith('.egg-info'):
                return f[:-9]

    def command(self):
        if sys.argv[2] != 'setup':
            print "Unknown pages command:", sys.argv[2]
            return

        print """Adding Zeroisp Database Definition to your TG Project"""
        print """==================================================="""

        package_name = self._get_package_name()
        if package_name is None:
            print 'Cannot upgrade an uninstalled project, try python setup.py develop first.'
            return
        package_name = package_name.replace('.', os.sep)
        package_dir = os.path.join(here, package_name)

        model_init_file_name = os.path.join(package_dir, 'model', '__init__.py')
        #websetup_file_name = os.path.join(package_dir, 'websetup', 'bootstrap.py')
        websetup_file_name = os.path.join(package_dir, 'websetup.py')

        if not os.path.exists(model_init_file_name) or not os.path.exists(websetup_file_name):
            print 'This does not appear to be a TurboGears2 application'
            return

        #make certain pages has not already been added to the project
        model_init_file = open(model_init_file_name, 'r')
        data = model_init_file.read()
        if not model_init_template in data:
            model_init_file.close()
            model_init_file = open(model_init_file_name, 'a')
            model_init_file.write(model_init_template)

        # add in the template code to the base of websetup.py
        websetup_file = open(websetup_file_name, 'r')
        data = websetup_file.read()
        if not websetup_template in data:
            websetup_file.close()
            websetup_file = open(websetup_file_name, 'a')
            websetup_file.write(websetup_template)

        #setup babel
        print "Setting up Babel for your application..."
        os.system('python setup.py extract_messages')
        for language in self.options.languages.split(','):
            os.system('python setup.py init_catalog -l %s'%language)
        os.system('python setup.py compile_catalog')

        #find the ini file:
        ini_file = None
        for arg in sys.argv[2:]:
            if arg.endswith('.ini'):
                ini_file = arg

        # call paster setup-app
        if ini_file:
            os.popen2('paster setup-app '+ini_file)
            import time
            time.sleep(2)
        else:
            print 'Database not setup: no ini file provided.'
